<template>
	<view class="topic-select-page">
		<!-- 顶部固定区域 -->
		<view class="fixed-header" :style="{ paddingTop: statusBarHeight + 'px' }">
			<u-search
				placeholder="输入感兴趣的话题"
				v-model="searchKeyword"
				:showAction="false"
				@change="handleSearch"
			/>
			<view class="selected-count">
				多选 <text class="count-num">{{ selectedCount }}</text>
			</view>
		</view>

		<!-- 主内容区域 -->
		<view class="main-content" :style="{ paddingTop: headerHeight + 'px' }">
			<!-- 左侧分类栏 -->
			<scroll-view scroll-y class="category-sidebar">
				<view
					v-for="(category, index) in categories"
					:key="category.id"
					class="category-item"
					:class="{ 'active': currentCategoryIndex === index }"
					@click="selectCategory(index)"
				>
					<text class="category-name">{{ category.name }}</text>
					<image v-if="category.icon" :src="category.icon" class="category-icon" mode="aspectFit"></image>
				</view>
			</scroll-view>

			<!-- 右侧话题列表 -->
			<scroll-view scroll-y class="topic-list-container">
				<!-- 搜索结果列表 -->
				<view v-if="searchKeyword" class="topic-list">
					<view
						v-for="item in filteredTopics"
						:key="item.topicId"
						class="topic-item"
						@click="toggleTopicSelection(item)"
					>
						<view class="topic-info">
							<view class="hashtag-icon">
								<u-icon name="/static/release/icon_jh.png" size="28"></u-icon>
							</view>
							<text class="topic-name">{{ item.title }}</text>
						</view>
						<view class="checkbox" :class="{ 'checked': item.selected }"></view>
					</view>
					<u-empty v-if="filteredTopics.length === 0" text="未找到相关话题" mode="search" marginTop="100"></u-empty>
				</view>
				
				<!-- 分类话题列表 -->
				<view v-else class="topic-list">
					<view
						v-for="item in currentCategoryTopics"
						:key="item.topicId"
						class="topic-item"
						@click="toggleTopicSelection(item)"
					>
						<view class="topic-info">
							<view class="hashtag-icon">
								<u-icon name="/static/release/icon_jh.png" size="28"></u-icon>
							</view>
							<text class="topic-name">{{ item.title }}</text>
						</view>
						<view class="checkbox" :class="{ 'checked': item.selected }"></view>
					</view>
				</view>
			</scroll-view>
		</view>
	</view>
</template>

<script>
import { getTopicsList } from '@/request/api.js';

export default {
	data() {
		return {
			statusBarHeight: 0,
			headerHeight: 0,
			searchKeyword: '',
			currentCategoryIndex: 1, // 默认选中"近期推荐"
			categories: [], // 从API获取
			eventChannel: null, // 页面间通信通道
		};
	},
	computed: {
		// 计算当前选中的分类下的话题列表
		currentCategoryTopics() {
			if (this.categories.length === 0) return [];
			return this.categories[this.currentCategoryIndex]?.topics || [];
		},
		// 计算所有已选中的话题数量
		selectedCount() {
			return this.categories.reduce((total, category) => {
				const count = category.topics.filter(topic => topic.selected).length;
				return total + count;
			}, 0);
		},
		// 根据搜索关键词过滤所有话题
		filteredTopics() {
			if (!this.searchKeyword) return [];
			const keyword = this.searchKeyword.toLowerCase();
			const allTopics = this.categories.flatMap(cat => cat.topics);
			return allTopics.filter(topic => topic.title.toLowerCase().includes(keyword));
		}
	},
	onLoad() {
		const systemInfo = uni.getSystemInfoSync();
		this.statusBarHeight = systemInfo.statusBarHeight;
		this.$nextTick(() => {
			const query = uni.createSelectorQuery().in(this);
			query.select('.fixed-header').boundingClientRect(data => {
				if (data) this.headerHeight = data.height;
			}).exec();
		});

		this.eventChannel = this.getOpenerEventChannel();
		this.fetchAndProcessTopics();
	},
	onUnload() {
		// 页面卸载时，回传最终选中的话题
		if (this.eventChannel) {
			const allSelectedTopics = this.categories
				.flatMap(cat => cat.topics)
				.filter(topic => topic.selected);
			
			this.eventChannel.emit('acceptDataFromTopicSelectPage', {
				selectedTags: allSelectedTopics
			});
		}
	},
	methods: {
		async fetchAndProcessTopics() {
			uni.showLoading({ title: '加载中...' });
			try {
				const res = await getTopicsList({ pageNum: 1, pageSize: 999 }); // 获取所有话题
				if (res.data && res.data.rows) {
					// 增加一个“我的”分类
					const myCategory = { id: 'my', name: '我的', topics: [] };
					
					// 格式化后端返回的数据，并增加 selected 状态
					const formattedCategories = res.data.rows.map(cat => {
						let topicsArray = []; // 1. 先创建一个空的 topics 数组作为默认值
						
						// 2. 检查 cat.keywords 是否存在且不为空
						if (cat.keywords) {
							try {
								// 3. 尝试解析，并判断解析结果是否为数组
								let parsedKeywords = (typeof cat.keywords === 'string') ? JSON.parse(cat.keywords) : cat.keywords;
								
								if (Array.isArray(parsedKeywords)) {
									topicsArray = parsedKeywords;
								}
							} catch (e) {
								// 4. 如果解析失败，说明它可能是个普通字符串，尝试用逗号分割
								if (typeof cat.keywords === 'string') {
									topicsArray = cat.keywords.split(',').filter(item => item.trim() !== ''); // .filter(Boolean) 过滤掉空字符串
								}
								console.warn('解析 keywords 失败，已尝试按逗号分割。原始值:', cat.keywords);
							}
						}
					
						// 5. 现在可以安全地对 topicsArray 使用 .map()
						const topics = topicsArray.map(topicName => ({
							id: cat.topicId, // 注意：这里的 id 可能需要调整，topic本身应该有自己的id
							title: topicName, // 这里使用了 topicName，因为原始代码是 (topic => ({ name: topic }))
							selected: false
						}));
					
						return {
							...cat,
							id: cat.topicId,
							name: cat.title,
							topics: topics // 使用我们安全处理后的 topics 数组
						};
					});
					
					// 模拟图标
					const recCat = formattedCategories.find(c => c.name === '旅游偏好');
					if (recCat) recCat.icon = '/static/release/icon_hot.png';
					const foodCat = formattedCategories.find(c => c.name === '自驾');
					if (foodCat) foodCat.icon = '/static/release/icon_ms.png';
					const dryGoodsCat = formattedCategories.find(c => c.name === '户外探险');
					if (dryGoodsCat) dryGoodsCat.icon = '/static/release/icon_gh.png';
					
					
					this.categories = [myCategory, ...formattedCategories];
					
					// 监听并处理初始数据
					this.eventChannel.on('sendInitialData', ({ initialSelectedTags }) => {
						this.initializeSelection(initialSelectedTags);
					});
				}
			} catch (error) {
				uni.showToast({ title: '话题加载失败', icon: 'none' });
			} finally {
				uni.hideLoading();
			}
		},
		initializeSelection(initialTags) {
			
			if (!initialTags || initialTags.length === 0) return;
			const initialIds = new Set(initialTags.map(tag => tag.topicId));
			this.categories.forEach(category => {
				category.topics.forEach(topic => {
					if (initialIds.has(topic.topicId)) {
						this.$set(topic, 'selected', true);
					}
				});
			});
		},
		selectCategory(index) {
			this.currentCategoryIndex = index;
			this.searchKeyword = ''; // 切换分类时清空搜索
		},
		toggleTopicSelection(topic) {
			this.$set(topic, 'selected', !topic.selected);
		},
		handleSearch() {
			// 输入时自动过滤，无需额外处理
		}
	}
};
</script>

<style lang="scss" scoped>
.topic-select-page {
	display: flex;
	flex-direction: column;
	height: 100vh;
	background-color: #FFFFFF;
}

.fixed-header {
	position: fixed;
	top: 10rpx;
	left: 0;
	right: 0;
	z-index: 99;
	background-color: #FFFFFF;
	padding: 20rpx 30rpx;
	box-sizing: border-box;
	display: flex;
	align-items: center;

	.selected-count {
		font-size: 30rpx;
		white-space: nowrap;
		margin-left: 20rpx;
		.count-num {
			color: #FE6B28;
			font-weight: bold;
			margin: 0 4rpx;
		}
	}
}

.main-content {
	flex: 1;
	display: flex;
	overflow: hidden;
}

.category-sidebar {
	width: 200rpx;
	background-color: #FFF8F5;
	height: calc(100% - 60rpx);
	flex-shrink: 0;
	border-radius: 70rpx;
	margin-left: 30rpx;
	padding: 30rpx 0;

	.category-item {
		position: relative;
		display: flex;
		align-items: center;
		justify-content: center;
		height: 90rpx;
		font-size: 30rpx;
		transition: all 0.2s;

		&::before {
			content: '';
			position: absolute;
			left: 20rpx;
			top: 50%;
			transform: translateY(-50%);
			width: 7rpx;
			height: 0;
			background-color: #FE6B28;
			transition: height 0.2s;
		}

		&.active {
			background-color: #fff;
			color: #333;
			font-weight: bold;
			&::before {
				height: 20rpx;
			}
		}
		.category-icon {
			position: absolute;
			top: 8rpx;
			right: 8rpx;
			width: 40rpx;
			height: 40rpx;
		}
	}
}

.topic-list-container {
	flex: 1;
	background-color: #fff;
	height: 100%;
	
	.topic-list {
		padding: 0 30rpx;
	}

	.topic-item {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 25rpx 0;
		// border-bottom: 1rpx solid #F0F0F0;

		&:last-child {
			border-bottom: none;
		}

		.topic-info {
			display: flex;
			align-items: center;
			.hashtag-icon {
				text-align: center;
				margin-right: 20rpx;
			}
			.topic-name {
				font-size: 30rpx;
			}
		}

		.checkbox {
			width: 36rpx;
			height: 36rpx;
			border-radius: 50%;
			border: 1rpx solid #E0E0E0;
			background-color: #F5F5F5;
			position: relative;
			transition: all 0.2s;

			&.checked {
				background-color: #FE6B28;
				border-color: #FE6B28;
				&::after {
					content: '✓';
					color: #fff;
					font-size: 24rpx;
					font-weight: bold;
					position: absolute;
					top: 50%;
					left: 50%;
					transform: translate(-50%, -50%);
				}
			}
		}
	}
}
</style>